import { useEffect, useState } from "react";

const useCountDown = (countdown:number, callback: Function) =>{
    const [time, setTime] = useState(countdown);
    const [isActive, setIsActive] = useState(false);

    useEffect(() => {
        let interval: NodeJS.Timeout | undefined;

        if (isActive && time > 0) {
            interval = setInterval(() => {
                setTime((prevTime) => prevTime - 1);
            }, 1000);
        } else if (time === 0) {
            setIsActive(false);
            callback();
        }

        return () => {
            if (interval) clearInterval(interval);
        };
    }, [isActive, time]);

    const start = () => {
        setIsActive(true);
    };

    const stop = () => {
        setIsActive(false);
    };

    const reset = () => {
        setTime(countdown);
        setIsActive(false);
    };

    return { time, isActive, start, stop, reset };
}

export default useCountDown;